<template>
  <div class="product-detail">
    <el-card class="product-info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">产品信息</span>
          <div class="header-buttons">
            <el-button type="primary" :icon="EditPen" @click="handleEdit" v-if="!isReadonly">编辑</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="产品编码">{{ productInfo.productCode }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ productInfo.productName }}</el-descriptions-item>
        <el-descriptions-item label="产品型号">{{ productInfo.model }}</el-descriptions-item>
        <el-descriptions-item label="产品类别">{{ productInfo.category }}</el-descriptions-item>
        <el-descriptions-item label="产品类型">
          <el-tag :type="getTypeTagType(productInfo.type)" size="small">{{ getTypeText(productInfo.type) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="计量单位">{{ productInfo.unit }}</el-descriptions-item>
        <el-descriptions-item label="规格" :span="2">{{ productInfo.specification }}</el-descriptions-item>
        <el-descriptions-item label="版本号">{{ productInfo.version }}</el-descriptions-item>
        <el-descriptions-item label="产品状态">
          <el-tag :type="getStatusType(productInfo.status)">{{ getStatusText(productInfo.status) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工艺路线ID">{{ productInfo.routeId || "未分配" }}</el-descriptions-item>
        <el-descriptions-item label="创建人">{{ productInfo.createdBy }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ productInfo.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ productInfo.updatedBy }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ productInfo.updatedTime }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="product-operations-card" shadow="hover" v-if="!isReadonly">
      <template #header>
        <div class="card-header">
          <span class="card-title">产品操作</span>
        </div>
      </template>

      <div class="operation-buttons">
        <el-button type="success" :icon="Check" @click="handleEnable" v-if="canEnable">启用产品</el-button>
        <el-button type="warning" :icon="Close" @click="handleDisable" v-if="canDisable">禁用产品</el-button>
        <el-button type="primary" :icon="Edit" @click="handleChangeVersion">变更版本</el-button>
        <el-button type="info" :icon="Document" @click="handleUpdateBOM">更新BOM</el-button>
        <el-button type="primary" :icon="Link" @click="handleAssignRoute" v-if="!productInfo.routeId">分配工艺路线</el-button>
        <el-button type="warning" :icon="Unlink" @click="handleUnassignRoute" v-if="productInfo.routeId">解绑工艺路线</el-button>
        <el-button type="success" :icon="Select" @click="handleApprove" v-if="canApprove">审核通过</el-button>
        <el-button type="danger" :icon="Close" @click="handleReject" v-if="canReject">审核驳回</el-button>
        <el-button type="danger" :icon="Delete" @click="handleDelete" v-if="canDelete">删除产品</el-button>
      </div>
    </el-card>

    <!-- BOM信息卡片 -->
    <el-card class="bom-info-card" shadow="hover" v-if="productInfo.bom && showBomSection">
      <template #header>
        <div class="card-header">
          <span class="card-title">BOM清单信息</span>
        </div>
      </template>

      <el-descriptions :column="3" border class="bom-descriptions">
        <el-descriptions-item label="BOM版本">{{ productInfo.bom.bomVersion }}</el-descriptions-item>
        <el-descriptions-item label="BOM类型">{{ productInfo.bom.bomType }}</el-descriptions-item>
        <el-descriptions-item label="BOM状态">
          <el-tag :type="productInfo.bom.status === '启用' ? 'success' : 'warning'" size="small">
            {{ productInfo.bom.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="BOM来源">{{ productInfo.bom.source }}</el-descriptions-item>
        <el-descriptions-item label="生效时间">{{ formatDateTime(productInfo.bom.effectiveDate) }}</el-descriptions-item>
        <el-descriptions-item label="失效时间">{{ formatDateTime(productInfo.bom.expiredDate) || '永久有效' }}</el-descriptions-item>
      </el-descriptions>

      <div class="bom-items-section">
        <h4 class="section-title">物料清单</h4>
        <el-table :data="productInfo.bom.items" border style="width: 100%">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="materialCode" label="物料编码" width="120" />
          <el-table-column prop="materialName" label="物料名称" width="200" />
          <el-table-column prop="quantity" label="数量" width="100" align="right" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        </el-table>
      </div>
    </el-card>

    <!-- 产品表单抽屉 -->
    <ProductForm ref="formDrawerRef" />

    <!-- 变更版本对话框 -->
    <el-dialog v-model="versionDialogVisible" title="变更产品版本" width="400px">
      <el-form :model="versionForm" ref="versionFormRef" :rules="versionRules" label-width="100px">
        <el-form-item label="当前版本">
          <el-input v-model="productInfo.version" disabled />
        </el-form-item>
        <el-form-item label="新版本号" prop="newVersion">
          <el-input v-model="versionForm.newVersion" placeholder="请输入新版本号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="versionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleVersionConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配工艺路线对话框 -->
    <el-dialog v-model="routeDialogVisible" title="分配工艺路线" width="400px">
      <el-form :model="routeForm" ref="routeFormRef" :rules="routeRules" label-width="100px">
        <el-form-item label="工艺路线" prop="routeId">
          <el-select v-model="routeForm.routeId" placeholder="请选择工艺路线" style="width: 100%">
            <el-option
              v-for="route in routeOptions"
              :key="route.id"
              :label="route.routeName"
              :value="route.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="routeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRouteConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核驳回对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="审核驳回" width="400px">
      <el-form :model="rejectForm" ref="rejectFormRef" :rules="rejectRules" label-width="100px">
        <el-form-item label="驳回原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRejectConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ProductDetail">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { EditPen, Check, Close, Edit, Document, Link, Unlink, Select, Delete } from "@element-plus/icons-vue";
import ProductForm from "./form.vue";
import {
  getProductById,
  getProductBOM,
  enableProduct,
  disableProduct,
  deleteProduct,
  changeProductVersion,
  updateProductBOM,
  assignProductRoute,
  unassignProductRoute,
  approveProduct,
  rejectProduct,
  type Product
} from "@/api/modules/product";
import { getRouteList } from "@/api/modules/route";
import { PageHelper } from "@/utils/pageHelper";

const route = useRoute();
const router = useRouter();

const productId = ref<number>(Number(route.params.id));
const productInfo = ref<Product.ProductListItem>({} as Product.ProductListItem);
const loading = ref(false);

// 版本变更对话框
const versionDialogVisible = ref(false);
const versionFormRef = ref<FormInstance>();
const versionForm = reactive({
  newVersion: ""
});
const versionRules = {
  newVersion: [{ required: true, message: "请输入新版本号", trigger: "blur" }]
};

// 分配工艺路线对话框
const routeDialogVisible = ref(false);
const routeFormRef = ref<FormInstance>();
const routeForm = reactive({
  routeId: null as number | null
});
const routeRules = {
  routeId: [{ required: true, message: "请选择工艺路线", trigger: "change" }]
};
const routeOptions = ref<any[]>([]);

// 审核驳回对话框
const rejectDialogVisible = ref(false);
const rejectFormRef = ref<FormInstance>();
const rejectForm = reactive({
  reason: ""
});
const rejectRules = {
  reason: [{ required: true, message: "请输入驳回原因", trigger: "blur" }]
};

// 计算是否为只读模式
const isReadonly = computed(() => {
  return ["deleted"].includes(productInfo.value.status);
});

// 计算各种操作的可用性
const canEnable = computed(() => {
  return ["created", "disabled"].includes(productInfo.value.status);
});

const canDisable = computed(() => {
  return ["enabled"].includes(productInfo.value.status);
});

const canApprove = computed(() => {
  return ["created", "enabled"].includes(productInfo.value.status);
});

const canReject = computed(() => {
  return ["created", "enabled"].includes(productInfo.value.status);
});

const canDelete = computed(() => {
  return ["created", "disabled"].includes(productInfo.value.status);
});

// 获取状态类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "info",
    enabled: "success",
    disabled: "warning",
    approved: "primary",
    rejected: "danger",
    deleted: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    created: "已创建",
    enabled: "已启用",
    disabled: "已禁用",
    approved: "已审核",
    rejected: "已驳回",
    deleted: "已删除"
  };
  return statusMap[status] || status;
};

// 获取产品类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    RAW_MATERIAL: "info",
    SEMI_FINISHED: "warning", 
    FINISHED: "success"
  };
  return typeMap[type] || "info";
};

// 获取产品类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    RAW_MATERIAL: "原材料",
    SEMI_FINISHED: "半成品",
    FINISHED: "成品"
  };
  return typeMap[type] || type;
};

// 是否显示BOM部分
const showBomSection = computed(() => {
  return productInfo.value.type === 'SEMI_FINISHED' || productInfo.value.type === 'FINISHED';
});

// 格式化日期时间
const formatDateTime = (dateTime: string | undefined) => {
  if (!dateTime) return '';
  return new Date(dateTime).toLocaleString('zh-CN');
};

// 获取产品详情
const getProductDetail = async () => {
  loading.value = true;
  try {
    const res = await getProductById(productId.value);
    productInfo.value = res.data;
    
    // 获取BOM信息（通过单独的API）
    await getBOMInfo();
  } catch (error) {
    console.error("获取产品详情失败:", error);
    ElMessage.error("获取产品详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取BOM信息
const getBOMInfo = async () => {
  try {
    const res = await getProductBOM(productId.value);
    productInfo.value.bom = res.data;
  } catch (error) {
    console.warn("获取BOM信息失败:", error);
    // BOM信息获取失败不影响产品详情的展示
    productInfo.value.bom = undefined;
  }
};

// 获取工艺路线选项
const getRouteOptions = async () => {
  try {
    const res = await getRouteList({ current: 1, size: 1000 });
    const pageData = PageHelper.parsePage(res.data);
    routeOptions.value = pageData.records;
  } catch (error) {
    console.error("获取工艺路线列表失败:", error);
  }
};

// 产品表单抽屉引用
const formDrawerRef = ref<InstanceType<typeof ProductForm>>();

// 编辑产品
const handleEdit = () => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...productInfo.value },
    getTableList: getProductDetail
  };
  formDrawerRef.value?.open(params);
};

// 启用产品
const handleEnable = async () => {
  try {
    await enableProduct(productId.value);
    ElMessage.success("产品启用成功");
    getProductDetail();
  } catch (error) {
    console.error("产品启用失败:", error);
    ElMessage.error("产品启用失败");
  }
};

// 禁用产品
const handleDisable = async () => {
  try {
    await disableProduct(productId.value);
    ElMessage.success("产品禁用成功");
    getProductDetail();
  } catch (error) {
    console.error("产品禁用失败:", error);
    ElMessage.error("产品禁用失败");
  }
};

// 变更版本
const handleChangeVersion = () => {
  versionForm.newVersion = "";
  versionDialogVisible.value = true;
};

// 确认变更版本
const handleVersionConfirm = async () => {
  if (!versionFormRef.value) return;

  await versionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await changeProductVersion(productId.value, {
          newVersion: versionForm.newVersion
        });
        ElMessage.success("版本变更成功");
        versionDialogVisible.value = false;
        getProductDetail();
      } catch (error) {
        console.error("版本变更失败:", error);
        ElMessage.error("版本变更失败");
      }
    }
  });
};

// 更新BOM
const handleUpdateBOM = async () => {
  try {
    await updateProductBOM(productId.value);
    ElMessage.success("BOM更新成功");
    getProductDetail();
  } catch (error) {
    console.error("BOM更新失败:", error);
    ElMessage.error("BOM更新失败");
  }
};

// 分配工艺路线
const handleAssignRoute = () => {
  routeForm.routeId = null;
  routeDialogVisible.value = true;
  getRouteOptions();
};

// 确认分配工艺路线
const handleRouteConfirm = async () => {
  if (!routeFormRef.value) return;

  await routeFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await assignProductRoute(productId.value, {
          routeId: routeForm.routeId!
        });
        ElMessage.success("工艺路线分配成功");
        routeDialogVisible.value = false;
        getProductDetail();
      } catch (error) {
        console.error("工艺路线分配失败:", error);
        ElMessage.error("工艺路线分配失败");
      }
    }
  });
};

// 解绑工艺路线
const handleUnassignRoute = async () => {
  ElMessageBox.confirm("确认解绑当前工艺路线吗？", "解绑确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await unassignProductRoute(productId.value, productInfo.value.routeId!);
        ElMessage.success("工艺路线解绑成功");
        getProductDetail();
      } catch (error) {
        console.error("工艺路线解绑失败:", error);
        ElMessage.error("工艺路线解绑失败");
      }
    })
    .catch(() => {
      // 取消解绑
    });
};

// 审核通过
const handleApprove = async () => {
  ElMessageBox.confirm(`确认审核通过产品 "${productInfo.value.productName}" 吗？`, "审核确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await approveProduct(productId.value);
        ElMessage.success("产品审核通过");
        getProductDetail();
      } catch (error) {
        console.error("产品审核失败:", error);
        ElMessage.error("产品审核失败");
      }
    })
    .catch(() => {
      // 取消审核
    });
};

// 审核驳回
const handleReject = () => {
  rejectForm.reason = "";
  rejectDialogVisible.value = true;
};

// 确认审核驳回
const handleRejectConfirm = async () => {
  if (!rejectFormRef.value) return;

  await rejectFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await rejectProduct(productId.value, {
          reason: rejectForm.reason
        });
        ElMessage.success("产品审核驳回");
        rejectDialogVisible.value = false;
        getProductDetail();
      } catch (error) {
        console.error("产品审核驳回失败:", error);
        ElMessage.error("产品审核驳回失败");
      }
    }
  });
};

// 删除产品
const handleDelete = async () => {
  ElMessageBox.confirm(`确认删除产品 "${productInfo.value.productName}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteProduct(productId.value);
        ElMessage.success("产品删除成功");
        router.push("/product");
      } catch (error) {
        console.error("产品删除失败:", error);
        ElMessage.error("产品删除失败");
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 返回
const goBack = () => {
  router.back();
};

// 页面加载时获取数据
onMounted(() => {
  getProductDetail();
});
</script>

<style scoped>
.product-detail {
  padding: 20px;
}

.product-info-card,
.product-operations-card,
.bom-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.bom-items-section {
  margin-top: 20px;
}

.section-title {
  margin: 0 0 15px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.bom-descriptions {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}
</style>